<?php

namespace app\admin\controller\coursetype;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;

/**
 * 课程类型管理
 *
 * @icon fa fa-list
 */
class Coursetype extends Backend
{
    /**
     * Coursetype模型对象
     */
    protected $model = null;
    protected $noNeedRight = ['index', 'lists', 'liststree'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Coursetype');
        $this->modelValidate = true;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 获取城市和学校过滤参数
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");
            
            // 调试日志
            error_log("Coursetype Index - city_id: $city_id, school_id: $school_id");

            $total = $this->model
                ->where($where);
                
            // 添加城市过滤
            if (!empty($city_id)) {
                $total = $total->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                $total = $total->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }
            
            // 添加学校过滤
            if (!empty($school_id)) {
                $total = $total->where("school_id", "=", $school_id);
            }
            
            $total = $total->where('status', '<>', -1)
                ->count();

            $list = $this->model
                ->where($where);
                
            // 添加城市过滤
            if (!empty($city_id)) {
                $list = $list->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }
            
            // 添加学校过滤
            if (!empty($school_id)) {
                $list = $list->where("school_id", "=", $school_id);
            }
            
            $list = $list->where('status', '<>', -1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            $tree = Tree::instance();
            $tree->init($list, 'parent_id');
            $list = $tree->getTreeList($tree->getTreeArray(0), 'name');
            $data = array();
            for ($i = 0; $i < count($list); $i++) {
                $v = $list[$i];
                if($v['level']==0) {
                    $v['name'] = "{$v['name']}";
                }elseif($v['level']==1) {
                    $v['name'] = preg_replace_callback("/^(\&nbsp\;)((?:\s|├|\&nbsp\;|│|├|└)*?)(.*)$/Uisx",function ($em){
                        return "{$em[1]}".str_replace("&nbsp;","&nbsp;&nbsp;",$em[2])."{$em[3]}";
                    },$v['name']);
                }elseif($v['level']==2) {
                    $v['name'] = preg_replace_callback("/^(\&nbsp\;)((?:\s|\&nbsp\;|\│|\├|└)*?)(.*)$/Uisx",function ($em){
                        return "{$em[1]}".str_replace("&nbsp;","&nbsp;&nbsp;",$em[2])."{$em[3]}";
                    },$v['name']);
                }
                $data[] = [
                    'id' => $v['id'],
                    'parent' => $v['parent_id'] ? $v['parent_id'] : '#',
                    'city_id' => model("Cityarea")->getCity_idTextAttr($v['city_id'],$v),
                    'school_id' => model("School")->getSchool_idTextAttr($v['school_id'],$v),
                    'name' => $v['name'],
                    'description' => $v['description'],
                    'icon' => $v['icon'],
                    'color' => $v['color'],
                    'sort_order' => $v['sort_order'],
                    'is_active' => $v['is_active'],
                    'level' => $v['level'],
                    'status' => $v['status'],
                    'weigh' => $v['weigh'],
                    'create_time' => $v['create_time'],
                    'update_time' => $v['update_time']
                ];
            }

            $result = array("total" => $total, "rows" => $data);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 限制层级不能超过三级
                if (isset($params['level']) && $params['level'] > 3) {
                    return json(['code'=>0,'msg'=>'课程类型最多只能分为三级']);
                }
                
                // 自动插入session中的城市和学校ID
                if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                    $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                }
                if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                    $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                }
                
                // 调试日志
                error_log("Coursetype Add - Auto inserted city_id: " . ($params['city_id'] ?? 'null') . ", school_id: " . ($params['school_id'] ?? 'null'));
                
                // 默认状态为正常
                $params['status'] = isset($params['status']) ? $params['status'] : 1;
                $params['is_active'] = isset($params['is_active']) ? $params['is_active'] : 1;
                $params['create_time']=date('Y-m-d H:i:s');
                unset($params['delete_time']);
                unset($params['update_time']);
                $params['update_time']="2025-10-13 10:10:10";
                $result = $this->model->allowField(true)->save($params);
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($this->model->getError());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 限制层级不能超过三级
                if (isset($params['level']) && $params['level'] > 3) {
                    return json(['code'=>0,'msg'=>'课程类型最多只能分为三级']);
                }
                
                // 自动插入session中的城市和学校ID（如果当前记录没有设置的话）
                if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                    if (empty($row['city_id'])) {
                        $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                    }
                }
                if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                    if (empty($row['school_id'])) {
                        $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                    }
                }
                
                // 调试日志
                error_log("Coursetype Edit - Auto inserted city_id: " . ($params['city_id'] ?? 'null') . ", school_id: " . ($params['school_id'] ?? 'null'));
                
                try {
                    $params['update_time'] = date('Y-m-d H:i:s');
                    unset($params['delete_time']);
                    unset($params['create_time']);
                    
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 获取课程类型列表
     */
    public function lists()
    {
        $where = "where status=1";
        $page = 1;
        $pagesize = 50;
        
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn = preg_split("/\,/", $keyValue);
                    for($i = 0; $i < count($nn); $i++) {
                        $where .= " and $keyField='{$nn[$i]}'";
                    }
                }
            }
        }

        $sql = "select id,name from fa_course_type $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);
        $total = db()->query("select count(1) as c from fa_course_type $where")[0];
        
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    /**
     * 获取课程类型树形结构
     */
    public function liststree()
    {
        $list = $this->model->where('status', 1)->order('weigh desc, id asc')->select();
        $list = collection($list)->toArray();
        
        $tree = Tree::instance();
        $tree->init($list, 'parent_id');
        $treeList = $tree->getTreeList($tree->getTreeArray(0), 'name');
        
        $data = [];
        foreach ($treeList as $v) {
            // 只允许三级
            if ($v['level'] > 3) continue;
            $name = strip_tags($v['name']);
            $data[] = [
                'id' => $v['id'],
                'parent_id' => $v['parent_id'],
                'name' => $name,
                'level' => $v['level'],
            ];
        }
        return json(['list' => $data, 'code' => 1]);
    }

    /**
     * 切换状态
     */
    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result = $this->model->where("id", "=", $ids)->field("status")->find();
            $v = $result->status == 1 ? 0 : 1;
            $this->model->where("id", "=", $ids)->update('`status` = -1');
            $this->success('切换成功!');
        } catch (\think\exception\PDOException $e) {
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            $this->error('切换失败!' . $e->getMessage());
        }
    }

    public function del($ids='')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            return json(['code' => 400, 'msg' => '没有选中任何记录']);
        }

        try {
            $result = Db::name('fa_course_type')
                ->whereIn('id', $ids)
                ->delete();

            if ($result) {
                return json(['code' => 1, 'msg' => '删除成功']);
            } else {
                return json(['code' => 400, 'msg' => '删除失败']);
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '服务器错误：' . $e->getMessage()]);
        }
    }
} 